Previous Book Contents Book Index Next

Inside Macintosh: AppleScript Language Guide / Part 2 - AppleScript Language Reference
Chapter 7 - Control Statements / Repeat Statements


Repeat With (loopVariable) In (list)

In the Repeat With (loopVariable) In (list) form of the Repeat statement, the looping variable is a reference to an item in a list. The number of iterations is equal to the number of items in the list. In the first iteration, the value of the variable is item 1 of list (where list is the list you specified in the first line of the statement), in the second iteration, its value is item 2 of list, and so on.

SYNTAX
repeat with loopVariable in list
   [ statement ]...
end [ repeat ]
where

loopVariable is any previously defined variable or a new variable you define in the Repeat statement (see "Notes").

list is a list or a reference (such as words 1 thru 5) whose value is a list. list can also be a record; AppleScript coerces the record to a list (see "Notes").

statement is any AppleScript statement.

EXAMPLE
The following example numbers the paragraphs of a document with the Repeat With (loopVariable) In (list) form of the Repeat statement. The value of the reference paragraphs (the paragraphs of document "List") is a list of the paragraphs in the document.

tell document "List"   set paragraphNum to 1
   repeat with n in paragraphs
      set paragraph paragraphNum to ÿ         (paragraphNum as string) & " " & contents of n
      set paragraphNum to paragraphNum + 1
   end repeat
end tell
NOTES
You can use an existing variable as the looping variable in a Repeat statement or define a new one in the Repeat statement. You cannot change the value of the looping variable in the loop body. The variable is undefined after the loop has been executed, but you can redefine it outside the loop.

AppleScript evaluates loopVariable in list as item 1 of list, item 2 of list, item 3 of list, and so on until it reaches the last item in the list:

repeat with i in {1, 2, 3, 4}
   set x to i
end repeat

--result: item 4 of {1, 2, 3, 4}
To get the value of an item in the list, you must use the contents of operator:

repeat with i in {1, 2, 3, 4}
   set x to contents of i
end repeat

--result: 4
If the value of list is a record, AppleScript coerces the record to a list by stripping the property labels. For example, {a:1, b:2, c:3} becomes
{1, 2, 3}.


Previous Book Contents Book Index Next

© Apple Computer, Inc.
13 JUL 1996